var datagrid = null;
var projectId = null;
var costId = null;
var costIdArr = null;
//插入or修改标志:0,新增 1,修改
var upsert = 0;

$(function() {
	initDialog();
	initMsgDatagird();
	
	$("#addCostA").bind("click", function(){
		upsert = 0;
		MZ.clearForm("costForm");
		$("#projectId").attr("disabled",false); 
		var liSize = $("#othercostField li").length;
		for(i = 2; i<liSize; i++){
			$('#othercostLI'+i).remove();
		}
		$("#gmtRefund").datepicker("setDate", new Date());  
		$("#ui-dialog-title-addCostDialog").text("新增费用（单位：元）");
		MZ.openDialog("addCostDialog");
	});
	
	$("#updateCostA").bind("click", function(){
		upsert = 1;
		costId = null;
		var rowVals = datagrid.getRowValues();
		//reset
		if(rowVals.length == 1){
			rowVal = rowVals[0];
			costId = rowVal.id;
			$("#projectId").attr("disabled",true); 
			$("#projectId").val(rowVal["projectName"]);
			var liSize = $("#othercostField li").length;
			for(i = 2; i<liSize; i++){
				$('#othercostLI'+i).remove();
			}
			for(var key in rowVal){
				$("#"+key).val(rowVal[key]);
			}
			var otherData = eval( "(" + rowVal["otherDetail"] + ")" );
			var otherSize = otherData.length;
			var obj = null;
			var otherCost = null;
			var liId = null;
			for(var i in otherData){
				obj = otherData[i];
				if(i == 0){
					$("#othercostLI1 input[name='otherCost']").val(obj.cost);
					$("#othercostLI1 select[name='otherCost']").val(obj.id);
				}else{
					liId = (i*1+1);
					otherCost=$('#othercostLI1').clone(true);
					otherCost.insertBefore('#addOtherCostLi');
					otherCost.attr("id","othercostLI"+liId);
					$("#othercostLI"+liId+" input[name='otherCost']").val(obj.cost);
					$("#othercostLI"+liId+" select[name='otherCost']").val(obj.id);
					otherCost.show();
				}
			}
			if(otherSize > 1){
				$("#othercostLI"+otherSize+" a[name='delOther']").show();
			}
			$("#totalCurrencySPAN").text(rowVal["totalCost"]);
			
			$("#gmtRefund").datepicker("setDate", new Date());  
			$("#ui-dialog-title-addCostDialog").text("修改费用（单位：元）");
			MZ.openDialog("addCostDialog");
		}else{
			MZ.showMsg("请选择一行记录修改!");
		}
	});
	
	$("#delCostA").bind("click", function(){
		costIdArr = datagrid.getRowValue(2);
		if(costIdArr.length >= 1){
			MZ.openDialog("dialog-confirm");
		}else{
			MZ.showMsg("请选择一行记录删除!");
		}
	});
		
	$('#addOtherCost').bind('click',function(){
		var liSize = $("#othercostField li").length;
		var otherCost=$('#othercostLI1').clone(true);
		otherCost.insertBefore('#addOtherCostLi');
		otherCost.attr("id","othercostLI"+liSize)
		$("#othercostLI"+liSize+" input[name='otherCost']").val("");
		$('#othercostField li a[name="delOther"]').each(function(i){
			$("#othercostLI"+(i+1)+" a[name='delOther']").hide();
		});
		$("#othercostLI"+liSize+" a[name='delOther']").show();
		otherCost.show();
	});
	
	$('#othercostField a[name="delOther"]').bind('click',function(){
		var liSize = $("#othercostField li").length-1;
		//update totalCurrency
		var otherCostVal = $("#othercostLI"+liSize+" input[name='otherCost']").val();
		otherCostVal = $.trim(otherCostVal) * 1;
		if(otherCostVal != ""){
			if($("#totalCurrencySPAN").text() != ""){
				var totalVal = ($("#totalCurrencySPAN").text() * 1) - otherCostVal;
				totalVal = MZ.toDecimal(totalVal, MZ.CURRENCY_ROUND);
				$("#totalCurrencySPAN").text(totalVal);
			}
		}
		var otherCost=$(this).parents("li");
		otherCost.remove();
		liSize = $("#othercostField li").length-1;
		if(liSize != 1){
			$("#othercostLI"+liSize+" a[name='delOther']").show();
		}
		
	});
	
	$("#projectId").autocomplete('/project/newproject/autoFillProjct', {
		minChars: 0,
		width: 450,
		matchContains: false,
		autoFill: true,
		mustMatch: true,
		dataType: 'json',
		//加入对返回的json对象进行解析函数，函数返回一个数组      
		parse: function(data) {  
			var rows = [];  
		    for(var i=0; i<data.length; i++){  
		    	rows[i] = {   
		    		 data:data[i].id +"-"+data[i].name,   
		    		 value:data[i].id,   
		    		 result:data[i].name   
		        };   
		      }  
		    return rows;  
		},  
		formatItem: function(row, i, n) {
		    return row;        
		}
	}).result(function(event, data, formatted) {
		projectId = null;
		if(typeof(data)!="undefined" && data.indexOf("-")!=-1){
			projectId = data.split("-")[0];
		}
	});
	
	//绑定金额输入框keyup事件
	//当输入框数量more时，需要采用total-old+new更新total值
	//不宜再全局运算
	$("#costForm input.currency-type").keyup(function(event){ 
		//console.log("oldVal in key up: %d", oldVal);
		var reg = /^-?\d+\.{0,}\d{0,}$/;
		if(!reg.test($(this).val())){
			$(this).val("");
		}
		var totalVal = 0;
		$("#costForm input.currency-type").each(function(){
			totalVal += $(this).val()*1;
		});
		totalVal = MZ.toDecimal(totalVal, MZ.CURRENCY_ROUND);
		$("#totalCurrencySPAN").text(totalVal);
	});
	
	//init datapicker
	$("#gmtRefund").datepicker("option", "defaultDate", new Date());  
	$("#gmtRefund").datepicker("option", "maxDate", new Date());
	
	$("#submitBtn").bind("click", function(){
		if(upsert == 0){
			addCost();
		}else if(upsert == 1){
			updateCost();
		}
		
	});
	$("#resetBtn").bind("click", function(){
		MZ.clearForm("costForm");
	});
	
	$("#searchA").bind("click", function(){
		searchCost();
	});
	
	$("#resetA").bind("click", function(){
		$("#projectNameText").val("");
	});
});

function initDialog(){
	//DIALOG//
	$('#addCostDialog').dialog({
		resizable: false,
		autoOpen: false,
		width: 600,
		height: 500,
		modal: true
	});
	
	$( "#dialog-confirm" ).dialog({
		resizable: false,
		autoOpen: false,
		height:180,
		modal: true,
		buttons: {
			"确认删除": function() {
				delCost();
				$( this ).dialog( "close" );
			},
			"取消": function() {
				$( this ).dialog( "close" );
			}
		}
	});
}
//init message datagird
//get json data from server
function initMsgDatagird(){
	datagrid = $("#msgDatagird").flexigrid({
		url: "outsidecost/selectForPage.json",
		colModel : [
		    {display: "ID", name : "id", width : 90, sortable : true, hide: true},
	        {display: "项目名称", name : "projectName", width : 400, sortable : true},
			{display: "总合同", name : "totalValue", width : 90, sortable : true, process:formatCost},
			{display: "已完成(%)", name : "completedValue", width : 90, sortable : true, process:formatPercent},
			{display: "预核算完成", name : "budgetcalcCplValue", width : 90, sortable : true, process:formatCost},
			{display: "报销人", name : "refundUser", width : 90, sortable : true, hide: true},
			{display: "报销时间", name : "gmtRefund", width : 90, sortable : true, process:formatTime},
			{display: "地质勘测", name : "geosurveyCost", width : 90, sortable : true, process:formatCost},
			{display: "测量", name : "surveyCost", width : 90, sortable : true, process:formatCost},
			{display: "内业", name : "designCost", width : 90, sortable : true, process:formatCost},
			{display: "其他", name : "otherCost", width : 90, sortable : true, process:formatCost},
			{display: "DETAIL", name : "otherDetail", width : 90, sortable : true, hide: true},
			{display: "合计", name : "totalCost", width : 120, sortable : true, process:formatCost}
		]
    });
}

//funciton onSelectRow required
//update flexigrid onselectrow function
//if you need't use onselect row
//let this function blank to do nothing
function onSelectRow(tr){
	
}
//格式化datagrid显示
function formatTime(tdDiv, pid){
	return $(tdDiv).text().substr(0, 10);
}
function formatCost(tdDiv, pid){
	var cost = $(tdDiv).text();
	if(cost == "0"){
		return "";
	}
	return MZ.toDecimal(cost / MZ.CURRENCY_PRECISION , MZ.CURRENCY_ROUND);
}
function formatPercent(tdDiv, pid){
	var val = $(tdDiv).text();
	if(val != ""){
		val += "%";
	}
	return val;
}
function searchCost(){
	var projectName = $("#projectNameText").val();
	var params = [{name: "projectName", value: projectName}];
	$("#msgDatagird").flexOptions({newp: 1, params: params}).flexReload();
}

function addCost(){
	var params = $('#costForm').serializeObject();
	params["projectId"] = Number(projectId);
	params["refundUser"] = "refundUser"
	var costDataArr = new Array();
	var dictName = "";
	var liId = null;
	var cost = null;
	var otherCost = 0;
	$("#othercostField select[name='otherCost']").each(function(i){
		if($(this).val() != null || $(this).val() != ""){
			liId = $(this).parents("li").attr("id");
			cost = $("#"+liId+" input[name='otherCost']").val() * 1;
			otherCost += cost * 1;
			dictName = $(this).find("option:selected").text();
			costDataArr.push("{'cost':"+cost+",'id':"+$(this).val()+",'name':'"+dictName+"'}");
		}
	});
	
	for(var key in params){
		if(key.indexOf("Cost") != -1){
			//params[key] = params[key] * MZ.CURRENCY_PRECISION;
			params[key] = MZ.toDecimal(params[key] * MZ.CURRENCY_PRECISION, MZ.CURRENCY_ROUND);
		}
	}
	params["otherCost"] = otherCost * MZ.CURRENCY_PRECISION;
	params["otherDetail"] = "["+costDataArr.toString()+"]";
	if(!validForm(params)){
		return false;
	}
	params = $.toJSON(params);
	//MZ.showMsg(params);
	$.ajax({
		url : "outsidecost/addOutsideCost",
		type : "post",
		data : "data="+params,
		beforeSend : function() {
		},
		success : function(result) {
			if(result.succeed){
				MZ.reloadDatagrid("msgDatagird");
			}else{
				MZ.showMsg(result.message);
			}
			MZ.closeDialog("addCostDialog");
		},
		error: function(result){
			MZ.showMsg(result);
		}
	});
}

function updateCost(){
	var params = $('#costForm').serializeObject();
	params["projectId"] = null;
//	costId
	params["id"] = costId;
	var costDataArr = new Array();
	var dictName = "";
	var liId = null;
	var cost = null;
	var otherCost = 0;
	$("#othercostField select[name='otherCost']").each(function(i){
		if($(this).val() != null || $(this).val() != ""){
			liId = $(this).parents("li").attr("id");
			cost = $("#"+liId+" input[name='otherCost']").val() * 1;
			otherCost += cost * 1;
			dictName = $(this).find("option:selected").text();
			costDataArr.push("{'cost':"+cost+",'id':"+$(this).val()+",'name':'"+dictName+"'}");
		}
	});
	
	for(var key in params){
		if(key.indexOf("Cost") != -1){
			params[key] = MZ.toDecimal(params[key] * MZ.CURRENCY_PRECISION, MZ.CURRENCY_ROUND);
		}
	}
	params["otherCost"] = otherCost * MZ.CURRENCY_PRECISION;
	params["otherDetail"] = "["+costDataArr.toString()+"]";
	if(!validForm(params)){
		return false;
	}
	params = $.toJSON(params);
	//MZ.showMsg(params);
	$.ajax({
		url : "outsidecost/updateOutsideCost",
		type : "post",
		data : "data="+params,
		beforeSend : function() {
		},
		success : function(result) {
			if(result.succeed){
				MZ.reloadDatagrid("msgDatagird");
			}else{
				MZ.showMsg(result.message);
			}
			MZ.closeDialog("addCostDialog");
		},
		error: function(result){
			MZ.showMsg(result);
		}
	});
}

function delCost(){
	var params = {"ids":costIdArr.toString()};
	$.ajax({
		url : "outsidecost/delOutsideCost",
		type : "post",
		data : params,
		beforeSend : function() {
		},
		success : function(result) {
			if(result.succeed){
				MZ.reloadDatagrid("msgDatagird");
			}else{
				MZ.showMsg(result.message);
			}
			MZ.closeDialog("addCostDialog");
		},
		error: function(result){
			MZ.showMsg(result);
		}
	});
}

//params : json type
function validForm(params){
	//金额正则验证
	var reg = /^-?\d+\.{0,}\d{0,}$/;
	//PROJECT
	if(upsert == 0){
		if($.trim(params.projectId) == "" || params.projectId == 0){
			MZ.showMsg("请选择一个项目!");
			return false;
		}
	}
	//refundUser
	//if($.trim(params.refundUser) == ""){
		//MZ.showMsg("报销人不能为空!");
		//return false;
	//}
	//gmtRefund
	if($.trim(params.gmtRefund) == ""){
		MZ.showMsg("报销时间不能为空!");
		return false;
	}
	//wageCost
	//keyup事件限制了金额输入，不再做金额验证...
	if($.trim(params.wageCost) != ""){
		if(!reg.test(params.wageCost)){
			MZ.showMsg("请输入正确的工资/奖金金额!");
			return false;
		}		
	}
	//验证总金额
	var totalCurrency = 0;
	$("#costForm input.currency-type").each(function(){
		totalCurrency += $(this).val()*1;
	});
	if(totalCurrency == 0){
		MZ.showMsg("未输入有效的报销项!");
		return false;
	}
	//otherCost
	var liId = null;
	var cost = null;
	$("#othercostField select[name='otherCost']").each(function(i){
		liId = $(this).parents("li").attr("id");
		cost = $("#"+liId+" input[name='otherCost']").val();
		if($(this).val() == null || $(this).val() == ""){
			if(i != 0){
				MZ.showMsg("未选择有效的其他报销项!");
				return false;
			}else{
				if(cost != ""){
					MZ.showMsg("未选择有效的其他报销项!");
					return false;
				}
			}
		}else{
			if(cost == ""){
				MZ.showMsg("未输入有效的其他报销项!");
				return false;
			}
		}
	});
	return true;
}

